import { useEffect, useState } from 'react';
import Modals from '@/components/modals/Modals';
import { ConfigProvider, Form, ModalProps } from 'antd';
import { Select, Input, Button, Row, Col } from '@/components/eai-design';
import { PlusOutlined } from '@ant-design/icons';
import { SvgIcon } from '../icon';
import { Alert } from '../eai-design';
import { CreateHeaderSecretReq } from '@/common';
interface AuthDefaultData {
  type?: string;
  name?: string;
  password?: string;
  secret?: string;
  customAuth?: AuthCustomData[];
}
interface AuthCustomData {
  key?: string;
  value?: string;
  secret?: string;
}

interface Props extends ModalProps {
  title: string;
  onSubmitOk: (values: object) => void;
  onCancel: () => void;
  open: boolean;
  defaultValue: AuthDefaultData;
  infoMessage?: string;
}

const AddOrDditOrganiztionalModal = ({
  title,
  onSubmitOk,
  onCancel,
  open,
  defaultValue,
  infoMessage,
  ...props
}: Props) => {
  const [form] = Form.useForm();
  const typeList = [
    { value: '无', label: '无' },
    { value: 'Bearer', label: 'Bearer' },
    { value: 'Basic', label: 'Basic' },
    { value: '自定义', label: '自定义' },
  ];
  const [selectedType, setSelectedType] = useState<string>('');
  const [customAuthFields, setCustomAuthFields] = useState<any[]>([]);
  const [clickedFields, setClickedFields] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (form && defaultValue) {
      form.setFieldsValue(defaultValue);
      setSelectedType(defaultValue.type || '');
      if (defaultValue.customAuth) {
        setCustomAuthFields(defaultValue.customAuth);
      }
    }
    // console.log(defaultValue, '--defaultValue')
  }, [defaultValue]);

  useEffect(() => {
    if (open) {
      setClickedFields(new Set());
    } else {
      form.resetFields();
      setSelectedType('');
      setCustomAuthFields([]);
      setClickedFields(new Set());
    }
  }, [open]);

  const handleInputClick = (fieldName: string, fieldIndex?: number, hasSecret?: boolean) => {

    if (clickedFields.has(fieldName)) {
      return;
    }

    let fieldsToMark = [fieldName];
    if (fieldName === 'username' || fieldName === 'password') {
      fieldsToMark = ['username', 'password'];
    }

    setClickedFields(prev => new Set([...prev, ...fieldsToMark]));

    if (hasSecret) {
      form.setFieldValue(['customAuth', fieldIndex, 'value'], '');
      form.setFieldValue(['customAuth', fieldIndex, 'secret'], '');
    } else {
      if (defaultValue.secret) {
        form.setFieldValue('name', '');
        form.setFieldValue('username', '');
        form.setFieldValue('password', '');
        form.setFieldValue('secret', '');
      }
    }
  };

  const onSubmit = () => {
    form.submit();
  };

  const handleTypeChange = (value: string) => {
    setSelectedType(value);
  };

  const onFinish = (values: CreateHeaderSecretReq) => {
    let headerAuth: any = {};
    const valuesAny = values as any;

    if (values.type === 'Bearer') {
      headerAuth = {
        Bearer: {
          secret: valuesAny.secret || '',
          value: values.name
        }
      };
    } else if (values.type === 'Basic') {
      const username = values.username;
      const password = values.password || '';
      const credentials = `${username}:${password}`;
      const base64Credentials = Buffer.from(credentials).toString('base64');
      headerAuth = {
        Basic: {
          secret: valuesAny.secret || '',
          // value: base64Credentials
          username: values.username,
          password: values.password
        }
      };
    } else if (values.type === '自定义') {
      const customAuthObj: any = {};
      values.customAuth?.forEach((item, index) => {
        customAuthObj[item.key || ''] = {
          secret: item.secret || '',
          value: item.value || ''
        };
      });
      headerAuth = customAuthObj;
    }
    // 调用父组件的回调函数
    onSubmitOk(headerAuth);
  };

  return (
    <Modals {...props} title={title} open={open} onOk={onSubmit} onCancel={onCancel}>
      <ConfigProvider
        theme={{
          components: {
            Form: {
              labelColor: '#4E5969',
              itemMarginBottom: 24,
              // itemMarginBottom: 0,
            },
          },
        }}
      >
        {infoMessage && (
          <Alert message={infoMessage} type="info" className='!mb-2' />
        )}
        <Form layout="vertical" onFinish={onFinish} form={form}>
          <Form.Item
            label={
              <div className="flex items-center gap-1">
                <span>鉴权类型</span>
                <span className="text-error">*</span>
              </div>
            }
            name="type"
            required={false}
            rules={[{ required: true, message: '请选择鉴权类型' }]}
          >
            <Select
              options={typeList}
              className="custom-select"
              onChange={handleTypeChange}
            />
          </Form.Item>
          {selectedType === 'Bearer' && (
            <Form.Item
              label={
                <div className="flex items-center gap-2">
                  <span className="text-text-4 font-normal">值</span>
                  <span className="text-error">*</span>
                  <span className="text-[var(--text-tertiary)] ">（保存后不再以明文显示）</span>
                </div>
              }
              name="name"
              required={false}
              rules={[{ required: true, message: '请输入值' }]}
            >
              <Input
                onClick={() => handleInputClick('bearer')}
                type={defaultValue?.secret && !clickedFields.has('bearer') ? 'password' : 'text'}
                placeholder="请输入值"
                className="w-full focus:border-[#D9D9D9] focus:outline-none"
              />
            </Form.Item>
          )}
          {selectedType === 'Basic' && (
            <>
              <Form.Item
                label={
                  <div className="flex items-center gap-2">
                    <span className="text-text-4 font-normal">Username</span>
                    <span className="text-error">*</span>
                    <span className="text-[var(--text-tertiary)]">（保存后不再以明文显示）</span>
                  </div>
                }
                name="username"
                required={false}
                rules={[{ required: true, message: '请输入Username' }]}
              >
                <Input
                  onClick={() => handleInputClick('username')}
                  type={defaultValue.secret && !clickedFields.has('username') ? 'password' : 'text'}
                  placeholder="请输入Username"
                  className="w-full focus:border-[#D9D9D9] focus:outline-none" />
              </Form.Item>
              <Form.Item
                label={
                  <div className="flex items-center gap-2">
                    <span className="text-text-4 font-normal">Password</span>
                    <span className="text-error">*</span>
                    <span className="text-[var(--text-tertiary)] ">（保存后不再以明文显示）</span>
                  </div>
                }
                name="password"
                required={false}
                rules={[{ required: true, message: '请输入Password' }]}
              >
                <Input
                  onClick={() => handleInputClick('password')}
                  type={defaultValue.secret && !clickedFields.has('password') ? 'password' : 'text'}
                  placeholder="请输入Password"
                  className="w-full focus:border-[#D9D9D9] focus:outline-none" />
              </Form.Item>
            </>
          )}
          {selectedType === '自定义' && (
            <Form.List name="customAuth" initialValue={[{ key: '', value: '' }]}>
              {(fields, { add, remove }, { errors }) => (
                <>
                  <Row gutter={[16, 16]} style={{ width: '100%' }}>
                    <Col span={22}>
                      <Row gutter={[16, 16]}>
                        <Col span={10}>
                          <div className="text-text-4 font-normal">
                            键
                            <span className='text-error ml-1'>*</span>
                          </div>
                        </Col>
                        <Col span={14}>
                          <div className="text-text-4 font-normal ml-4">
                            值
                            <span className='text-error ml-1'>*</span>
                            <span className="text-[var(--text-tertiary)] ">（保存后不再以明文显示）</span>
                          </div>
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                  {fields.map((field, index) => {
                    const fieldData = customAuthFields[index] || {};
                    const hasSecret = !!fieldData.secret;

                    return (
                      <Row gutter={[16, 16]} style={{ width: '100%' }} key={field.key}>
                        <Col span={fields.length >= 2 ? 22 : 24}>
                          <Row gutter={[16, 16]}>
                            <Col span={10}>
                              <Form.Item
                                {...field}
                                name={[field.name, 'key']}
                                rules={[
                                  { required: true, message: '请输入键' },
                                  {
                                    validator: async (_, value) => {
                                      if (!value) return;
                                      const currentValues = form.getFieldValue('customAuth') || [];
                                      const currentIndex = field.name;

                                      if (typeof currentIndex !== 'number') return;

                                      const duplicateCount = currentValues.filter((item: any, idx: number) =>
                                        item && item.key === value && idx !== currentIndex
                                      ).length;

                                      if (duplicateCount > 0) {
                                        throw new Error('键不能重复');
                                      }
                                    }
                                  }
                                ]}
                              >
                                <Input placeholder="请输入键" />
                              </Form.Item>
                            </Col>
                            <Col span={14}>
                              <Form.Item
                                {...field}
                                name={[field.name, 'value']}
                                rules={[{ required: true, message: '请输入值' }]}
                              >
                                <Input
                                  type={hasSecret && !clickedFields.has(`custom-${index}`) ? 'password' : 'text'}
                                  placeholder="请输入值"
                                  onClick={() => handleInputClick(`custom-${index}`, index, hasSecret)}
                                  onChange={(e) => {
                                    form.setFieldValue(['customAuth', index, 'value'], e.target.value);
                                  }}
                                />
                              </Form.Item>
                            </Col>
                          </Row>
                        </Col>
                        {(fields.length >= 2 && <Col span={2}>
                          <div className='flex items-center h-8 cursor-pointer'>
                            <SvgIcon
                              icon="delete-icon"
                              size={16}
                              onClick={() => {
                                remove(field.name);
                                const newCustomAuthFields = [...customAuthFields];
                                newCustomAuthFields.splice(field.name, 1);
                                setCustomAuthFields(newCustomAuthFields);
                              }}
                              color='#000'
                            />
                          </div>
                        </Col>)}
                      </Row>
                    );
                  })}
                  <Form.Item>
                    <Button
                      onClick={() => {
                        add();
                        setCustomAuthFields([...customAuthFields, {}]);
                      }}
                      icon={<PlusOutlined />}
                      className="!bg-fill-1 border-2 !border-line-2"
                    >
                      新增
                    </Button>
                    <Form.ErrorList errors={errors} />
                  </Form.Item>
                </>
              )}
            </Form.List>
          )}
        </Form>
      </ConfigProvider>

    </Modals >
  );
};

export default AddOrDditOrganiztionalModal;
